#include "FileHelper.h"

FileHelper::FileHelper(fs::FS fs) : fs(fs)
{
}

size_t FileHelper::readFile(const char *path)
{
    File file = fs.open(path);
    if (!file || file.isDirectory())
    {
        return 0;
    }
    size_t size = file.available();
    if (size > 0)
    {
        buf.reset(new uint8_t[size]);
        file.read(buf.get(), size);
    }
    file.close();
    return size;
}

uint8_t *FileHelper::getFileContent()
{
    return buf.get();
}

size_t FileHelper::readFile(const char *path, uint8_t *buf)
{
    File file = fs.open(path);
    if (!file || file.isDirectory())
    {
        return 0;
    }
    size_t size = file.available();
    if (size > 0)
    {
        file.read(buf, size);
    }
    file.close();
    return size;
}
bool FileHelper::deleteFile(const char *path)
{
    return fs.remove(path);
}
bool FileHelper::writeFile(const char *path, const char *message)
{
    File file = fs.open(path, FILE_WRITE);
    if (!file)
    {
        return false;
    }
    bool ret = file.print(message);
    file.close();
    return ret;
}
bool FileHelper::writeFile(const char *path, JsonDocument doc)
{
    File file = fs.open(path, FILE_WRITE);
    if (!file)
    {
        return false;
    }
    size_t size = serializeJson(doc, file);
    file.close();
    return size > 0;
}
bool FileHelper::writeRawFile(const char *path, uint8_t *buf, size_t size)
{
    File file = fs.open(path, FILE_WRITE);
    if (!file)
    {
        return false;
    }
    bool ret = file.write(buf, size);
    file.close();
    return ret;
}
bool FileHelper::appendFile(const char *path, const char *message)
{
    File file = fs.open(path, FILE_APPEND);
    if (!file)
    {
        return false;
    }
    bool ret = file.print(message);
    file.close();
    return ret;
}

FileHelper::~FileHelper()
{
    buf.reset();
}
